﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeGenerateEngine.Common
{
    /// <summary>
    /// 日志服务
    /// </summary>
    class LogService 
    {

        public LogService()
        {
            //定义全局变量--指定文件存放路径 (当前路径向上找2层)
            log4net.GlobalContext.Properties["LogFileName"] = System.IO.Path.GetDirectoryName(new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath);
            log4net.GlobalContext.Properties["RevitName"] = "";

            //获取配置文件全称
            string str = "CodeGenerateEngine.Log4Net.config";
            //读取配置文件
            System.IO.Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(str);
            log4net.Config.XmlConfigurator.Configure(stream);
        }

        public void Error(string msg, string AppName = "")
        {
            log4net.ILog _infoLog = log4net.LogManager.GetLogger("ErrorLog");
            string NewMsg = CombineMsg(msg, AppName);
            _infoLog.Error(NewMsg);
        }

        public void Error(string msg, Exception ex, string AppName = "")
        {
            log4net.ILog _infoLog = log4net.LogManager.GetLogger("ErrorLog");
            string NewMsg = CombineMsg(msg, AppName);
            _infoLog.Error(NewMsg, GetException(ex));
        }

        public void Info(string msg, string AppName = "")
        {
            log4net.ILog _infoLog = log4net.LogManager.GetLogger("InfoLog");
            string NewMsg = CombineMsg(msg, AppName);
            _infoLog.Info(NewMsg);
        }

        public void Info(string msg, Exception ex, string AppName = "")
        {
            log4net.ILog _infoLog = log4net.LogManager.GetLogger("InfoLog");
            string NewMsg = CombineMsg(msg, AppName);
            _infoLog.Info(NewMsg, GetException(ex));
        }

        private string CombineMsg(string msg, string AppName = "")
        {
            StringBuilder builder = new StringBuilder();
            if (!string.IsNullOrEmpty(AppName))
            {
                builder.Append(string.Format("【{0}】", AppName));
                builder.Append(Environment.NewLine);
                builder.Append(string.Format("{0,24}", msg));
            }
            else
            {
                builder.Append(msg);
            }
            return builder.ToString();
        }

        public Exception GetException(Exception ex)
        {
            if (ex.InnerException != null)
            {
                return new Exception(ex.InnerException.Message, ex.InnerException);
            }
            else
            {
                return new Exception(ex.Message, ex);
            }
        }

    }
}
